package im.composer.persistent.xstream.converter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.BitSet;

import org.apache.commons.codec.binary.Base64;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class BitSetConverter implements Converter {

	@Override
	public boolean canConvert(@SuppressWarnings("rawtypes") Class arg0) {
		return BitSet.class.isAssignableFrom(arg0);
	}

	@Override
	public void marshal(Object arg0, HierarchicalStreamWriter arg1, MarshallingContext arg2) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(arg0);
			oos.flush();
			oos.close();
		} catch (IOException e) {
		}
		arg1.setValue(Base64.encodeBase64String(baos.toByteArray()));
	}

	@Override
	public Object unmarshal(HierarchicalStreamReader arg0, UnmarshallingContext arg1) {
		byte[] b = Base64.decodeBase64(arg0.getValue());
		ByteArrayInputStream bais = new ByteArrayInputStream(b);
		try {
			ObjectInputStream ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (IOException | ClassNotFoundException e) {
		}
		return null;
	}

}
